from websocket import create_connection
import serial
import time
import threading
import inv_RFID

class InventoryManagement:
	ws = None
	t_continue = False
	RFID_control = None

	def __init__(self,host,username,password):
		self.RFID_control = inv_RFID.RFID('/dev/ttyUSB0',115200)
		self.ws = create_connection(host)
		self.ws.send("login&&" +username + "&&" +password)
		status = self.ws.recv()
		print status
		if status == 'Login Failed !' : self.ws.close()

	def addData(self,pid,rfid_id):
		if self.ws.connected :
			self.ws.send("add&&" + pid + "=" + rfid_id)
			print "Sent",
			print "Receiving..."
			result =  self.ws.recv()
			print "Received '%s'" % result

	def read(self):
		while self.t_continue :
			readData = self.RFID_control.read(0x00,0x04)
			if(len(readData) > 0):
				self.ws.send("add&&"+readData)

	def command(self):
		readThread = threading.Thread(target=self.read)
		while True :
			buff = self.ws.recv()
			command = buff.split("&&")
			print command[0]
			if(command[0] == "CREAD"):
				print "starting"
				self.t_continue = True
				readThread = threading.Thread(target=self.read)
				readThread.daemon = True
				readThread.start()
				print "thread started"
			elif(command[0] == "CSTOP"):
				print "stoping"
				self.t_continue = False
				readThread.join()
				print "thread stopped"
			elif(command[0] == "CWRITE"):
				print "write"
				if(self.RFID_control.commandWriteTag(command[1])): self.ws.send("Re&&True")
				else : self.ws.send("Re&&False")


	def close(self):
		self.RFID_control.close()
		self.ws.close()

	def cal_checksum(self,a,b):
		return a^b

x = InventoryManagement("ws://invmanage.no-ip.org:8888/","root","root")
x.command()
#while True:
#   product_id = raw_input("\npid = ")
#   rfid_id = raw_input("rfid_id = ")   
#   if product_id == "end":
#      x.close()
#      break
#   else:	
#      x.addData(product_id,rfid_id)

